package com.aweqy.librarymanager.controller;

import com.aweqy.librarymanager.entity.Book;
import com.aweqy.librarymanager.service.BookService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/book")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping("/list")
    public Page<Book> list(@RequestParam(defaultValue = "1") int page,
                          @RequestParam(defaultValue = "10") int size,
                          @RequestParam(required = false) String title) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        if (title != null && !title.isEmpty()) {
            wrapper.like("title", title);
        }
        return bookService.page(new Page<>(page, size), wrapper);
    }

    @PostMapping("/add")
    public ResponseEntity<?> add(@RequestBody Book book) {
        if (!StringUtils.hasText(book.getIsbn()) || !StringUtils.hasText(book.getTitle()) || !StringUtils.hasText(book.getAuthor())) {
            return ResponseEntity.badRequest().body("ISBN、标题、作者不能为空");
        }
        if (bookService.lambdaQuery().eq(Book::getIsbn, book.getIsbn()).one() != null) {
            return ResponseEntity.badRequest().body("ISBN已存在，请勿重复添加");
        }
        boolean ok = bookService.save(book);
        if (!ok) {
            return ResponseEntity.status(500).body("保存失败，请联系管理员");
        }
        return ResponseEntity.ok(true);
    }

    @PostMapping("/update")
    public boolean update(@RequestBody Book book) {
        return bookService.updateById(book);
    }

    @PostMapping("/delete")
    public boolean delete(@RequestParam Integer id) {
        return bookService.removeById(id);
    }
} 